package routers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"news-cms/handlers"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.Use(Cors()) //默认跨域
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	r.POST("/register", handlers.Register)
	r.POST("/login", handlers.Login)
	r.POST("/add", handlers.Add)
	r.GET("/list", handlers.List)
	return r
}

//	func MiddleWare() gin.HandlerFunc {
//		return func(c *gin.Context) {
//			tokenString := c.Request.Header.Get("token")
//			fmt.Println("获取到token参数为：", tokenString)
//			if tokenString == "" {
//				c.JSON(200, gin.H{
//					"code": 500,
//					"msg":  "token为空",
//				})
//				c.Abort()
//			}
//			fmt.Println("中间件开始执行了")
//			// 设置变量到Context的key中，可以通过Get()取
//			c.Set("request", "中间件")
//			// 执行函数
//			c.Next()
//			// 中间件执行完后续的一些事情
//			status := c.Writer.Status()
//			fmt.Println("中间件执行完毕", status)
//			t2 := time.Since(t)
//			fmt.Println("time:", t2)
//		}
//	}
func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
